// Helper function to replace HH with H for 24 hours format, because H allows also single-digit hours
function adjustedTimeFormat() {
  return moment
    .localeData()
    .longDateFormat('LT')
    .replace(/HH/i, 'H');
}

export class DatePicker extends BlazeComponent {
  template() {
    return 'datepicker';
  }

  onCreated(defaultTime = '1970-01-01 08:00:00') {
    this.error = new ReactiveVar('');
    this.card = this.data();
    this.date = new ReactiveVar(moment.invalid());
    this.defaultTime = defaultTime;
    this.dateHH = new ReactiveVar([]);
    this.dateMM = new ReactiveVar([]);

    this.dateHH.set([
      '00',
      '01',
      '02',
      '03',
      '04',
      '05',
      '06',
      '07',
      '08',
      '09',
      '10',
      '11',
      '12',
      '13',
      '14',
      '15',
      '16',
      '17',
      '18',
      '19',
      '20',
      '21',
      '22',
      '23',
    ]);
    this.dateMM.set([
      '00',
      '05',
      '10',
      '15',
      '20',
      '25',
      '30',
      '35',
      '40',
      '45',
      '50',
      '55',
      '60',
    ]);
    this.showSetHour = new ReactiveVar(false);
    this.showSetMinute = new ReactiveVar(false);
  }

  startDayOfWeek() {
    const currentUser = Meteor.user();
    if (currentUser) {
      return currentUser.getStartDayOfWeek();
    } else {
      return 1;
    }
  }

  setDateHHShow() {
    return this.showSetHour.get();
  }
  setDateMMShow() {
    return this.showSetMinute.get();
  }
  onRendered() {
    document.getElementsByClassName('content-wrapper')[0].style.overflow =
      'initial';
    const self = this;
    const $picker = this.$('.js-datepicker')
      .datepicker({
        todayHighlight: true,
        todayBtn: 'linked',
        language: TAPi18n.getLanguage(),
        weekStart: this.startDayOfWeek(),
      })
      .on(
        'changeDate',
        function(evt) {
          this.find('#date').value = moment(evt.date).format('L');
          this.error.set('');
          const timeHHInput = this.find('#timeHH');
          const timeMMInput = this.find('#timeMM');
          timeHHInput.focus();
          if (!timeHHInput.value) {
            const currentDate = evt.date.getDate();
            const currentHour = evt.date.getHours();
            const currentMinute = evt.date.getMinutes();
            const defaultMoment = moment(
              currentHour > 0 ? evt.date : this.defaultTime,
            ); // default to 8:00 am local time
            const wholeTime = defaultMoment.format('LT');
            const wholeTime1 = defaultMoment.format('HH:mm');

            // console.log('--------self---------', self);
            // self.date.set(defaultMoment);
            // const defaultMoment = moment(
            //   currentHour > 0 ? evt.date : this.defaultTime,
            // ); // default to 8:00 am local time
            // timeInput.value = defaultMoment.format('LT');
            // timeHHInput.value = currentHour;
            // timeMMInput.value = currentMinute;
            // let isAM = wholeTime.substring(0, 2) ===
            //   '上午' || wholeTime.substring(0, 2) ===
            //   '中午' || wholeTime.substring(0, 2) ===
            //   '凌晨' ?
            //   true : false;
            // if (isAM) {
            //   if (!isNaN(Number(wholeTime.substring(3, 4)))) {
            //     timeHHInput.value = wholeTime.substring(2, 4);
            //   } else {
            //     timeHHInput.value = `0${wholeTime.substring(2, 3)}`;
            //   }
            // } else {
            //   if (!isNaN(Number(wholeTime.substring(3, 4)))) {
            //     timeHHInput.value =parseInt(wholeTime.substring(2, 4))===12?`${parseInt(wholeTime.substring(2, 4))}`: `${parseInt(wholeTime.substring(2, 4))+12}`;
            //   } else {
            //     timeHHInput.value = `${parseInt(wholeTime.substring(2, 3))+12}`;
            //   }
            // }
            // timeMMInput.value = wholeTime.substring(wholeTime.length - 2, wholeTime.length);

            timeHHInput.value = `${wholeTime1.substring(0, 2)}`;
            timeMMInput.value = `${wholeTime1.substring(3, 5)}`;
          }
        }.bind(this),
      );

    if (this.date.get().isValid()) {
      $picker.datepicker('update', this.date.get().toDate());
    }
  }

  setdateHH() {
    return this.dateHH.get();
  }
  setdateMM() {
    return this.dateMM.get();
  }
  showDate() {
    if (this.date.get().isValid()) return this.date.get().format('L');
    return '';
  }
  showTime() {
    if (this.date.get().isValid()) return this.date.get().format('LT');
    return '';
  }
  getWholeTime(hour, minute) {
    let wholeStr = '';
    const hourInt = parseInt(hour, 10);
    // const minuteInt = parseInt(minute,10);
    let hourStr =
      hour.substring(0, 1) === '0'
        ? hour.substring(1, 2)
        : hour.substring(0, 2);
    let preStr = '';
    if (TAPi18n.getLanguage() === 'zh-CN') {
      if (hourInt >= 0 && hourInt < 6) {
        preStr = '凌晨';
      } else if (hourInt >= 6 && hourInt < 12) {
        preStr = '早上';
      } else if (hourInt >= 12 && hourInt < 18) {
        preStr = '下午';
      } else if (hourInt >= 18 && hourInt < 24) {
        preStr = '晚上';
      }
      if (hourStr.length === 2 && parseInt(hourStr, 10) > 12) {
        hourStr = `${parseInt(hourStr, 10) - 12}`;
      }
      wholeStr = `${preStr}${hourStr}点${minute}`;
    } else {
      if (hourInt >= 0 && hourInt < 12) {
        preStr = 'AM';
      } else {
        preStr = 'PM';
      }
      if (hourStr.length === 2 && parseInt(hourStr, 10) > 12) {
        hourStr = `${parseInt(hourStr, 10) - 12}`;
      }
      wholeStr = `${hourStr}:${minute} ${preStr}`;
    }
    return wholeStr;
  }
  showTimeHour() {
    const wholeTime = this.date.get().format('HH:mm');

    if (this.date.get().isValid()) {
      return `${wholeTime.substring(0, 2)}`;

      //   const hhMM = this.date.get().format('LT');
      //   let isAM = this.date.get().format('LT').substring(0, 2) === '上午' ||
      //     this.date.get().format('LT').substring(0, 2) === '中午' || this.date
      //     .get().format('LT').substring(0, 2) === '凌晨' ?
      //     true : false;
      //   if (isAM) {
      //     if (!isNaN(Number(hhMM.substring(3, 4)))) {
      //       return hhMM.substring(2, 4);
      //     } else {
      //       return `0${hhMM.substring(2, 3)}`;
      //     }
      //   } else {
      //     if (!isNaN(Number(hhMM.substring(3, 4)))) {
      //       return `${parseInt(hhMM.substring(2, 4))+12}`;
      //     } else {
      //       return `${parseInt(hhMM.substring(2, 3))+12}`;
      //     }
      //   }
    }
    return '';
  }
  showTimeMinute() {
    const wholeTime = this.date.get().format('HH:mm');
    if (this.date.get().isValid()) {
      return `${wholeTime.substring(3, 5)}`;
      // const hhMM = this.date.get().format('LT');
      // return hhMM.substring(hhMM.length - 2, hhMM.length)
    }
    return '';
  }
  dateFormat() {
    return moment.localeData().longDateFormat('L');
  }
  timeFormat() {
    return moment.localeData().longDateFormat('LT');
  }

  events() {
    return [
      {
        'keyup .js-date-field'() {
          // parse for localized date format in strict mode
          const dateMoment = moment(this.find('#date').value, 'L', true);
          if (dateMoment.isValid()) {
            this.error.set('');
            this.$('.js-datepicker').datepicker('update', dateMoment.toDate());
          }
        },
        'keyup .js-time-field'() {
          // parse for localized time format in strict mode
          // const dateMoment = moment(this.find('#time').value, 'LT', true);
          // if (dateMoment.isValid()) {
          //   this.error.set('');
          // }
        },

        'input .js-time-hour'(evt) {
          const val = evt.target.value;
          if (parseInt(val, 10) > 23) {
            evt.target.value = '';
            evt.target.focus();
            this.error.set('invalid-date');
            return;
          }
          if (val.length > 3) {
            evt.target.value = val.substring(0, 2);
          }
        },
        'input .js-time-minute'(evt) {
          const val = evt.target.value;
          if (parseInt(val, 10) > 60) {
            evt.target.value = '';
            evt.target.focus();
            this.error.set('invalid-date');
            return;
          }
          if (val.length > 3) {
            evt.target.value = val.substring(0, 2);
          }
        },
        'click .js-time-hour'() {
          this.showSetHour.set(!this.showSetHour.get());
        },
        'click .js-time-minute'() {
          this.showSetMinute.set(!this.showSetMinute.get());
        },
        'click .js-set-hour-li'(evt) {
          document.getElementById('timeHH').value = evt.target.innerHTML;
          this.showSetHour.set(false);
        },
        'click .js-set-minute-li'(evt) {
          document.getElementById('timeMM').value = evt.target.innerHTML;
          this.showSetMinute.set(false);
        },
        'submit .edit-date'(evt) {
          evt.preventDefault();
          //if no time was given, init with 12:00
          const timeHH = evt.target.timeHH.value;
          const timeMM = evt.target.timeMM.value;
          if (timeHH.length !== 2 || timeMM.length !== 2) {
            this.error.set('invalid-date');
            return;
          }
          if (TAPi18n.getLanguage() === 'zh-CN') {
            const wholeTime = this.getWholeTime(timeHH, timeMM);
            let wholeDate = '';
            wholeDate = evt.target.date.value;
            const dateString = `${wholeDate} ${wholeTime}`;
            const newDate = moment(dateString, 'L LT', true);
            if (newDate.isValid()) {
              this._storeDate(newDate.toDate());
              Popup.close();
            } else {
              this.error.set('invalid-date');
              evt.target.date.focus();
            }
            const newCompleteDate = moment(
              dateString,
              `L ${adjustedTimeFormat()}`,
              true,
            );
            if (newCompleteDate.isValid()) {
              this._storeDate(newCompleteDate.toDate());
              Popup.close();
            } else if (!this.error) {
              this.error.set('invalid');
            }
          } else {
            const time =
            moment(new Date().setHours(timeHH, timeMM, 0)).format('LT') ||
            moment(new Date().setHours(12, 0, 0)).format('LT');
            const newTime = moment(time, adjustedTimeFormat(), true);
            const newDate = moment(evt.target.date.value, 'L', true);
            const dateString = `${evt.target.date.value} ${time}`;
            const newCompleteDate = moment(
              dateString,
              `L ${adjustedTimeFormat()}`,
              true,
            );
            if (!newTime.isValid()) {
              this.error.set('invalid-time');
              evt.target.time.focus();
            }
            if (!newDate.isValid()) {
              this.error.set('invalid-date');
              evt.target.date.focus();
            }
            if (newCompleteDate.isValid()) {
              this._storeDate(newCompleteDate.toDate());
              Popup.close();
            } else if (!this.error) {
              this.error.set('invalid');
            }
          }
        },
        'click .js-delete-date'(evt) {
          evt.preventDefault();
          this._deleteDate();
          Popup.close();
        },
      },
    ];
  }
}
